initMC = function () {
    var _mc = new MediaCentral();
    _mc.InitializeAllPanels();

    MediaCentral.Browse.PopulateAllVideos();
    $.ajaxSetup({ cache: false });

    $.ajax({
        url: "http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetAllTags",
        dataType: 'json',
        success: function (data) {
            var options = {
                source: function (request, response) {
                    response($.ui.autocomplete.filter(
						data, extractLast(request.term)));
                },
                select: function (event, ui) {
                    var terms = split(this.value);
                    terms.pop();
                    terms.push(ui.item.value);
                    terms.push("");
                    this.value = terms.join(",");
                    return false;
                },
                focus: function () {
                    return false;
                }
            }

            $('#tagsTextBoxLocalVid').autocomplete(options);
            $('#ytvidtags').autocomplete(options);
        }
    });

    split = function (val) {
        return val.split(/,\s*/);
    }

    extractLast = function (term) {
        return split(term).pop();
    }
}

MediaCentral = function () {
    this.InitializeAllPanels = function () {
        var ytadder = new MediaCentral.YouTube('YouTubeVideos');
        ytadder.wireAddVideo();
    }
}
MediaCentral.Global = function () { }

MediaCentral.Global.ShowGenericMessage = function (message) {
    SP.UI.Notify.addNotification(message);
}

MediaCentral.Browse = function () { }

MediaCentral.Browse.PopulateAllVideos = function () {
    MediaCentral.Browse.GetVideos('');
}

MediaCentral.Browse.GetVideos = function (webMethod) {
    var query = webMethod;
    if (query == '') {
        query = "GetAFewVideos?num=10";
        $('#browsetagsselected').hide();
    }
    $('#allvideos').empty();
    $('#allvideos').append('<img src="' + _spPageContextInfo.webServerRelativeUrl + '/MediaCentral/ajax-loader.gif" alt="loding" />');
    $.ajax({
        //url: "http://uvo1da8xh9fetrjrbtu.env.cloudshare.com/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetAFewVideos?num=10",
        url: "http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/" + query,
        dataType: 'json',
        success: function (data) {
            $('#allvideos').empty();
            $(data).each(function () {
                var item = $(this)[0];
                var tags = item.Tags.split(',');

                $('#allvideos').append("<div class='vidbox' vidid='" + item.VideoUrl + "'><div class='topvideosingle' style='background-image:url(" + item.Thumbnail + "); background-repeat: no-repeat; background-size: 100%'>"
				+ "<a class='vid_thumb' href='" + item.VideoUrl + "'><p class='vidtitle'>" + item.Title + "</p></a></div><div class='browsevidtags'></div></div>");

                $(tags).each(function () {
                    $('div[vidid="' + item.VideoUrl + '"] div.browsevidtags').append("<span class='browsetag'>" + $(this)[0] + "</span>");
                });

                if (item.IsLocalVid == true) {
                    $('a[href="' + item.VideoUrl + '"]').addClass('localVid');
                }
                else {
                    $('a[href="' + item.VideoUrl + '"]').addClass('youtubeVid');
                }
            });

            $('.localVid').each(function () {
                var vidUrl = $(this).attr('href');
                $(this).click(function () {
                    $(this).parent().append("<div id='vidpopup'></div><script type='text/javascript'>jwplayer('vidpopup').setup({modes: [{type: 'html5'},{type:'flash', src:'jwplayer/jwplayer.swf'}],'file':'" + vidUrl + "', 'width':'640', 'height':'480' }); $('#vidpopup').dialog({width: 640, height: 480, close: function(even, ui) { $(this).remove(); }});</script>");
                    return false;
                });
            });

            $('.youtubeVid').each(function () {
                var embedurl = $(this).attr('href');
                var vidTitle = $(this).find('.vidtitle').text();

                $(this).click(function () {
                    SP.UI.ModalDialog.showModalDialog({ url: embedurl, width: 600, height: 400, title: vidTitle });
                    return false;
                });
            });

            MediaCentral.Browse.WireTags();
        }
    });
}

MediaCentral.Browse.WireTags = function () {
    var webMethod = "GetAllVideosByTag?tag=";
    $('.browsetag').click(function () {
        $('#browsetagsselected').empty().show().append('<span>Tags: ' + $(this).text() + '</span>');
        MediaCentral.Browse.GetVideos(webMethod + $(this).text());
    });
}

MediaCentral.GlobalVideoRepository = function (locRepo, ytRepo) {
    this._locRepo = locRepo;
    this._ytRepo = ytRepo;

    this.getAllVideosAsJSON() = function () {

    }
}

MediaCentral.YouTube = function (ytlistname) {
    this._ytListName = ytlistname;

    this.wireAddVideo = function () {
        $('#ytlinkgobutton').click(function () {
            var vidId = $('#ytlinkbox').val();
            if (vidId.indexOf('http://') != -1) {
                var url = vidId;
                var qstring = url.split('?');
                var vars = qstring[1].split('&');
                for (var i = 0; i < vars.length; i++) {
                    var pair = vars[i].split('=');
                    if (pair[0] == 'v') {
                        vidId = pair[1];
                        $('#ytlinkbox').val(vidId);
                    }
                }
            }

            $.getJSON("http://gdata.youtube.com/feeds/api/videos/" + vidId + "?callback=?&alt=jsonc&v=2", function (data) {
                $('#add-yt-editdetails').show();
                var tags = "";
                $(data.data.tags).each(function () {
                    tags += $(this)[0] + ',';
                });
                tags.slice(0, -1);

                $('#ytvidtitle').val(data.data.title);
                $('#ytviddescription').val(data.data.description);
                $('#ytvidthumb').val(data.data.thumbnail.sqDefault);
                $('#ytvidtags').val(tags);
            });
        });

        $('#ytsavevid').click(function () {
            var id = $('#ytlinkbox').val();
            var title = $('#ytvidtitle').val();
            var desc = $('#ytviddescription').val();
            var thumb = $('#ytvidthumb').val();
            var tags = $('#ytvidtags').val();

            //MediaCentral.YouTube.saveYTVideo(title, desc, thumb, id, tags);
            MediaCentral.Manager.SaveVid("YouTube", title, desc, thumb, id, tags);

        });
    }
}

MediaCentral.LocalVideos = function () { }

MediaCentral.LocalVideos.DeleteVideo = function (listname, id) {
    var ctx = SP.ClientContext.get_current();
    var localVidListToDel = ctx.get_web().get_lists().getByTitle(listname);

    var listItem = localVidListToDel.getItemById(id);
    listItem.deleteObject();
    ctx.executeQueryAsync(MediaCentral.LocalVideos.DeleteVideoSuccess, MediaCentral.LocalVideos.DeleteVideoFail);
}

MediaCentral.LocalVideos.DeleteVideoSuccess = function (sender, args) {
    var manager = new MediaCentral.Manager();
    manager.PopulateEditBoxes();
    MediaCentral.Manager.WireEditControls();
    MediaCentral.Global.ShowGenericMessage('Video deleted!');
}

MediaCentral.LocalVideos.DeleteVideoFail = function (sender, args) {
    MediaCentral.Global.ShowGenericMessage('Failed to delete video!');
    MediaCentral.Global.ShowGenericMessage('Editing videos is disabled in Demo mode');
}

MediaCentral.LocalVideos.WireHandlers = function () {
    $('#uploadLocalVidbutton').unbind();
    $('#uploadLocalVidbutton').click(function () {
        SP.UI.ModalDialog.showModalDialog({
            url: "http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/Upload.aspx?List=%7B5B2FE2D6%2D755F%2D4F4F%2DAD51%2D69A703A9D8FB%7D&RootFolder=%2FLocalVideos&IsDlg=1",
            width: 650,
            height: 500
        });
    });
}

MediaCentral.Manager = function () {

    this.PopulateEditBoxes = function () {
        $.ajax({
            //url: top.location.host + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetAllVideos",
            url: "http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetAllVideos",
            dataType: 'json',
            success: function (data) {
                $('#allvideos').empty();
                $('#edit-local-vid-list').empty();
                $('#edit-vid-list').empty();

                $(data).each(function () {
                    var item = $(this)[0];
                    /*var selectList = null;
					
                    if (item.IsLocalVid == true) {
                    selectList = $('#edit-local-vid-list');
                    }
                    else {
                    selectList = $('#edit-vid-list');
                    }
                    */
                    $('#edit-local-vid-list').append("<option value='" + item.ID + "' desc='" + item.Description + "' thumb='" + item.Thumbnail + "' tags='" + item.Tags + "' localVid='" + item.IsLocalVid + "'>" + item.Title + "</option>");
                });

            }
        });
    }
}

MediaCentral.Manager.WireEditControls = function () {
    $('#edit-local-vid-list').unbind();
    $('#edit-local-vid-list').change(function () {
        var thumburl = $(this).find('option:selected').attr('thumb');
        if (thumburl == "null") thumburl = "";

        $('#titleTextboxLocalVid').val($(this).find('option:selected').text());
        $('#descTextboxLocalVid').val($(this).find('option:selected').attr('desc'));
        $('#thumbTextboxLocalVid').val(thumburl);
        $('#tagsTextBoxLocalVid').val($(this).find('option:selected').attr('tags'));
        $('#editlocalvideoid').val($(this).find('option:selected').val());

        $('#localVid').val($(this).find('option:selected').attr('localVid'));
    });

    $('#saveLocalVidChanges').unbind();
    $('#saveLocalVidChanges').click(function () {
        var id = $('#editlocalvideoid').val();
        var title = $('#titleTextboxLocalVid').val();
        var description = $('#descTextboxLocalVid').val();
        var thumb = $('#thumbTextboxLocalVid').val();
        var tags = $('#tagsTextBoxLocalVid').val();
        var localVid = $('#localVid').val();

        if (id == "") {
            alert('Choose a video first');
            return;
        }

        var listName = "";
        if (localVid == "false") {
            listName = "YouTubeVideos";
        } else {
            listName = "LocalVideos";
        }

        MediaCentral.Manager.UpdateVid(listName, title, description, thumb, id, tags)
    });

    $('#deleteLocalVid').unbind();
    $('#deleteLocalVid').click(function () {
        var localVid = $('#localVid').val();
        var id = $('#editlocalvideoid').val();

        if (id == "") {
            alert('Choose a video first');
            return;
        }

        var listName = "";
        if (localVid == "false") {
            listName = "YouTubeVideos";
        } else {
            listName = "LocalVideos";
        }

        if (confirm('Are you sure you want to delete this video?')) {
            MediaCentral.LocalVideos.DeleteVideo(listName, id);
        }
    });
}

MediaCentral.Manager.SaveVid = function (type, title, desc, thumb, id, tags) {
    $.ajax({
        url: encodeURI("http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/AddNewVideo?listType=" + type + "&title=" + title + "&description=" + desc + "&thumbnail=" + thumb + "&videoid=" + id + "&tags=" + tags),
        dataType: 'json',
        success: function (data) {
            MediaCentral.Global.ShowGenericMessage("Video added");
        },
        error: function () {
            //MediaCentral.Global.ShowGenericMessage("Failed to add video :(");
            MediaCentral.Global.ShowGenericMessage('Adding videos is disabled in Demo mode');
        }
    });
}

MediaCentral.Manager.UpdateVid = function (type, title, desc, thumb, id, tags) {
    $.ajax({
        url: encodeURI("http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/UpdateVideo?libName=" + type + "&id=" + id + "&title=" + title + "&description=" + desc + "&thumbnail=" + thumb + "&tags=" + tags),
        dataType: 'json',
        success: function (data) {
            MediaCentral.Global.ShowGenericMessage("Video saved");
            var manager = new MediaCentral.Manager();
            manager.PopulateEditBoxes();
            MediaCentral.Manager.WireEditControls();

        },
        error: function () {
            //MediaCentral.Global.ShowGenericMessage("Failed to update video :(");
            MediaCentral.Global.ShowGenericMessage('Editing videos is disabled in Demo mode');
        }
    });
}


MediaCentral.Find = function () { }

MediaCentral.Find.WireHandlers = function () {
    $('#searchbox').keyup(function () {
        $('#searchresults').empty();
        var query = $('#searchbox').val();
        if (query.length < 3) return;

        $('#searchresults').append('<img src="/MediaCentral/ajax-loader.gif" alt="loding" />');

        $.ajax({
            //url: top.location.host +  "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetVideosBySearchString?q=" + query,
            url: "http://" + top.location.host + _spPageContextInfo.webServerRelativeUrl + "/_layouts/MediaCentral.Services.SharePoint/MediaCentral.Services.MCService.svc/json/GetVideosBySearchString?q=" + query,
            dataType: 'json',
            success: function (data) {
                $('#searchresults').empty();
                $(data).each(function () {
                    var item = $(this)[0];
                    $('#searchresults').append("<div class='searchresultsingle'><div vidLink='" + item.VideoUrl + "' class='topvideosingle' style='background-image:url(" + item.Thumbnail + "); background-repeat: no-repeat; background-size: 100%'>"
						+ "<a class='vid_thumb' href='" + item.VideoUrl + "'></a></div><div class='searchresultdetail'><p>" + item.Title + "</p><p>" + item.Description + "</p><p>Tags: " + item.Tags + "</p><div style='clear:both'></div></div>");

                    if (item.IsLocalVid == true) {
                        $('div[vidLink="' + item.VideoUrl + '"]').addClass('localVid');
                    }
                    else {
                        $('div[vidLink="' + item.VideoUrl + '"]').addClass('youtubeVid');
                    }
                });

                $('#searchresults .localVid').each(function () {
                    var vidUrl = $(this).find('a').attr('vidLink');
                    $(this).click(function () {
                        $(this).parent().append("<div id='vidpopup'></div><script type='text/javascript'>jwplayer('vidpopup').setup({modes: [{type: 'html5'},{type:'flash', src:'jwplayer/jwplayer.swf'}],'file':'" + vidUrl + "', 'width':'640', 'height':'480' }); $('#vidpopup').dialog({width: 640, height: 480, close: function(even, ui) { $(this).remove(); }});</script>");
                        return false;
                    });
                });

                $('#searchresults .youtubeVid').each(function () {
                    var embedurl = $(this).find('a').attr('href');
                    var vidTitle = $(this).parent().find('.searchresultdetail p:first-child').text();

                    $(this).parent().click(function () {
                        SP.UI.ModalDialog.showModalDialog({ url: embedurl, width: 600, height: 400, title: vidTitle });
                        return false;
                    });
                });
            }
        });
    });
}


ExecuteOrDelayUntilScriptLoaded(initMC, "sp.js");

